import { ElMessage } from 'element-plus'
import axios from "axios";
import useUserStore from '@/store/modules/user'

const baseURL = "http://192.168.51.47:2000/admin";
const timeout = 15000;

export interface Result<T> {
    code: number;
    message: string;
    page?: number;
    size?: number;
    total?: number;
    data?: T;
}

const axiosInstance = axios.create({
    baseURL,
    timeout,
})



axiosInstance.interceptors.request.use(
    (config) => {
        const userStore = useUserStore()
        if (userStore.accessToken) {
            config.headers.Authorization = 'Bearer ' + userStore.accessToken
        }
        return config
    },
    (error) => {
        ElMessage({
            type: 'error',
            center: true,
            message: error.message
        })
        Promise.reject(error)
    }
);

axiosInstance.interceptors.response.use(
    (response) => {
        if (response.data.code !== 20000) {
            ElMessage({
                type: 'error',
                center: true,
                message: response.data.message
            })
            return Promise.resolve(response);
        }
        return Promise.resolve(response);
    },
    (error) => {
        ElMessage({
            type: 'error',
            center: true,
            message: error.message
        })
        return Promise.resolve(error);
    }
);

const request = {
    // get: (url: string, params: object = {}) => {
    //     return AxiosInstance({
    //         method: 'GET',
    //         url,
    //         params
    //     })
    // },
    // post: (url: string, data: object = {}) => {
    //     return AxiosInstance({
    //         method: 'POST',
    //         url,
    //         data
    //     })
    // }

    get: async function get<T>(url: string, params?: any): Promise<Result<T>> {
        const response = await axiosInstance.get<Result<T>>(url, { params });
        return response.data;
    },
    post: async function post<T>(url: string, data?: any): Promise<Result<T>> {
        const response = await axiosInstance.post<Result<T>>(url, data);
        return response.data;
    },
    put: async function put<T>(url: string, data?: any): Promise<Result<T>> {
        const response = await axiosInstance.put<Result<T>>(url, data);
        return response.data;
    },
    delete: async function del<T>(url: string, params?: any): Promise<Result<T>> {
        const response = await axiosInstance.delete<Result<T>>(url, { params });
        return response.data;
    }
}

export default request
